package com.bh.statistics.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bh.statistics.dao.TSysRegionMapper;
import com.bh.statistics.entity.TSysRegion;
import com.bh.statistics.entity.TSysRegionVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * RegionServiceImpl
 *
 * @author Ljy
 * @version 2023/09/05 17:07
 **/
@Service
public class RegionServiceImpl implements RegionService {
    @Resource
    TSysRegionMapper sysRegionMapper;

    @Override
    public List<TSysRegionVO> listData() {
        QueryWrapper<TSysRegion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("level","5").or().eq("level","6");
        QueryWrapper<TSysRegion> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("level","4");
        List<TSysRegion> tSysRegions = sysRegionMapper.selectList(queryWrapper);
        TSysRegion rootRegion = sysRegionMapper.selectOne(queryWrapper2);
        TSysRegionVO rootRegionVO = new TSysRegionVO();
        rootRegionVO.setId(String.valueOf(rootRegion.getId()));
        rootRegionVO.setPid(String.valueOf(rootRegion.getParentId()));
        rootRegionVO.setName(rootRegion.getName());
        rootRegionVO.setValue(rootRegion.getCode());

        TSysRegionVO tSysRegionVO = buildChildTree(rootRegionVO, tSysRegions);
        List<TSysRegionVO> result = new ArrayList<>();
        result.add(tSysRegionVO);
        return result;
    }

    @Override
    public List<TSysRegion> getAll() {
        QueryWrapper<TSysRegion> queryWrapper = new QueryWrapper<>();
        return sysRegionMapper.selectList(queryWrapper);
    }

    public TSysRegionVO buildChildTree(TSysRegionVO rootRegion,List<TSysRegion> list){
        List<TSysRegionVO> childTree = new ArrayList<>();
        for (TSysRegion treeNode : list) {
            TSysRegionVO tSysRegionVO = new TSysRegionVO();
            tSysRegionVO.setId(String.valueOf(treeNode.getId()));
            tSysRegionVO.setPid(String.valueOf(treeNode.getParentId()));
            tSysRegionVO.setName(treeNode.getName());
            tSysRegionVO.setValue(treeNode.getCode());

            if (tSysRegionVO.getPid().equals(rootRegion.getId())) {
                childTree.add(buildChildTree(tSysRegionVO,list));
            }
        }
        rootRegion.setChildren(childTree);
        return rootRegion;
    }
}
